'use strict'

// utils is a library of generic helper functions non-specific to axios

var toString = Object.prototype.toString

/**
 * Determine if a value is an Array
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is an Array, otherwise false
 */
export function isArray(val) {
  return toString.call(val) === '[object Array]'
}


/**
 * Determine if a value is an Object
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is an Object, otherwise false
 */
export function isObject(val) {
  return Object.prototype.toString.call(val) == '[object Object]'
  // return val !== null && typeof val === 'object'
}

/**
 * Determine if a value is a Date
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a Date, otherwise false
 */
export function isDate(val) {
  return toString.call(val) === '[object Date]'
}

/**
 * Determine if a value is a URLSearchParams object
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
 */
export function isURLSearchParams(val) {
  return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams
}


/**
 * Iterate over an Array or an Object invoking a function for each item.
 *
 * If `obj` is an Array callback will be called passing
 * the value, index, and complete array for each item.
 *
 * If 'obj' is an Object callback will be called passing
 * the value, key, and complete object for each property.
 *
 * @param {Object|Array} obj The object to iterate
 * @param {Function} fn The callback to invoke for each item
 */
export function forEach(obj, fn) {
  // Don't bother if no value provided
  if (obj === null || typeof obj === 'undefined') {
    return
  }

  // Force an array if not already something iterable
  if (typeof obj !== 'object') {
    /*eslint no-param-reassign:0*/
    obj = [obj]
  }

  if (isArray(obj)) {
    // Iterate over array values
    for (var i = 0, l = obj.length; i < l; i++) {
      fn.call(null, obj[i], i, obj)
    }
  } else {
    // Iterate over object keys
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        fn.call(null, obj[key], key, obj)
      }
    }
  }
}

/**
 * 是否为boolean 值
 * @param val
 * @returns {boolean}
 */
export function isBoolean(val) {
  return typeof val === 'boolean'
}

/**
 * 是否为真正的对象{} new Object
 * @param {any} obj - 检测的对象
 * @returns {boolean}
 */
export function isPlainObject(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]'
}



/**
 * Function equal to merge with the difference being that no reference
 * to original objects is kept.
 *
 * @see merge
 * @param {Object} obj1 Object to merge
 * @returns {Object} Result of all merge properties
 */
export function deepMerge(/* obj1, obj2, obj3, ... */) {
  let result = {}
  function assignValue(val, key) {
    if (typeof result[key] === 'object' && typeof val === 'object') {
      result[key] = deepMerge(result[key], val)
    } else if (typeof val === 'object') {
      result[key] = deepMerge({}, val)
    } else {
      result[key] = val
    }
  }
  for (let i = 0, l = arguments.length; i < l; i++) {
    forEach(arguments[i], assignValue)
  }
  return result
}


export const getUuid = function (len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [],
    i;
  radix = radix || chars.length;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

// 获取当天日期（返回格式xxxx-xx-xx）
export function getCurDate(spacer, type) {
  // 获取当天日期
  const date = new Date();
  // 获取当前日期年份
  const year = date.getFullYear();
  // 获取当前日期月份
  let month = date.getMonth() + 1;
  // 获取当前日期天
  let day = date.getDate();
  // 获取当前小时
  const hours = date.getHours();
  // 获取当前分钟
  const minutes = date.getMinutes();
  // 获取当前秒
  const seconds = date.getSeconds();
  // 判断当月份小于10月时显示 0月份
  month = month > 9 ? month : `0${month}`;
  // 判断当天小于10月时显示 0天
  day = day > 9 ? day : `0${day}`;
  spacer = spacer ? spacer : '-';
  // 组合默认时间
  let defaultTime = "";
  if (type == 'all') {
    defaultTime = `${year}${spacer}${month}${spacer}${day} ${hours}:${minutes}:${seconds}`;
  } else {
    defaultTime = `${year}${spacer}${month}${spacer}${day}`;
  }

  return defaultTime;
}

/**
 * 根据身份证获取计算用户出生日期和性别
 * IdCard 身份证号
 * types 1--获取性别 2--获取出生日期
 */
export function calGendAndBirth(IdCard, types) {
  if (types === 1) {
    //获取性别
    if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
      return "0";
    } else {
      return "1";
    }
  }
  if (types === 2) {
    //获取出生日期
    let birthday =
      IdCard.substring(6, 10) +
      "-" +
      IdCard.substring(10, 12) +
      "-" +
      IdCard.substring(12, 14);
    return birthday;
  }
}

// 校验手机号
export function checkPhone(tel) {
  const reg =
    /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
  if (reg.test(tel) || tel == '') {
    return true;
  } else {
    return false;
  }
}
// 校验邮箱
export function checkEmail(email) {
  const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if (reg.test(email) || email == '') {
    return true;
  } else {
    return false;
  }
}

/**
 * 弱提示用户信息
 * tips 用户提示信息
 * icon icon展示，默认不展示icon
 */

export function notify(tips, icon = 'none') {
  uni.showToast({
    title: tips,
    icon: icon,
    duration: 30000
  });
}

/**
 * 判断用户底部安全距离
 */
export function getSafe() {
  let filterList = [];
  let models = ["X", "XR", "XS", "11", "12", "13", "14", "15"];
  const osName = uni.getSystemInfoSync().osName; // 获取手机系统（ios、android、windows、macos、linux）
  const deviceModel = uni.getSystemInfoSync().model; // 获取手机模型（inphone/huawei/...）
  if (deviceModel) {
    filterList = models.filter(item => deviceModel.indexOf(item) > -1);
  }
  // osName == 'ios' &&
  return filterList.length > 0 ? true : false;
}

/**
 * 计算近一周  近一个月 近三个月的时间
 * @param { Number } days  需要计算的时间
 * @returns 年/月/日
 */
export function calcDate(days) {
  // 获取当前时间
  let current = new Date();
  let calcDate = null;
  if (days == '1w') {
    calcDate = new Date(current.getTime() - 7 * 24 * 3600 * 1000);
  } else {
    calcDate = new Date(current.getTime() - getDays(days) * 24 * 3600 * 1000);
  }
  // 设置计算时间
  current.setTime(calcDate);
  // 获取计算时间年份
  const year = current.getFullYear();
  // 获取计算时间月份
  let month = current.getMonth() + 1;
  // 获取计算时间天
  let day = current.getDate();
  // 判断当月份小于10月时显示 0月份
  month = month > 9 ? month : `0${month}`;
  // 判断当天小于10月时显示 0天
  day = day > 9 ? day : `0${day}`;
  return `${year}/${month}/${day}`;
}

/**
 * 计算天数
 * @returns 
 */
export function getDays(days) {
  const isLeapYear = false;
  const current = new Date('2022-01-01');
  const year = current.getFullYear();
  const month = current.getMonth() == 0 ? 1 : current.getMonth();
  let calcMonth = 0;
  if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
    isLeapYear = true
  }
  const monthMaps = {
    1: 31, 2: isLeapYear ? 29 : 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
  };
  if (days == '1m') {
    calcMonth = monthMaps[month];
  } else {
    const lastMonth = month - 1 == 0 ? 12 : month - 1;
    const llMonth = month - 2 == 0 ? 12 : (month - 2 == -1) ? 11 : month - 2;
    calcMonth = monthMaps[month] + monthMaps[lastMonth] + monthMaps[llMonth]
  }

  return calcMonth;
}